class PoPaymentsController < ApplicationController
  before_action :set_po_payment, only: [:show, :edit, :update, :destroy]
  before_action :set_po
  
  respond_to :html

  def index
    @po_payments = PoPayment.order(created_at: :desc).page(params[:page])
    respond_with(@po_payments)
  end

  def show
    respond_with(@po_payment)
  end

  def new
    @po_payment = PoPayment.new
    respond_with(@po_payment)
  end

  def edit
  end

  def create
    @po_payment = PoPayment.new(po_payment_params)
    PoPayment.transaction do 
      @po_payment.save      
      @po.update(amount_paid:@po.increase_amount_paid(@po_payment.amount)  , balance:@po.cal_balance )      
    end
    
    respond_with(@po)
  end

  def update
    # @po_payment.update(po_payment_params)
    respond_with(@po_payment)
  end

  def destroy
    PoPayment.transaction do
      amount = @po_payment.amount 
      @po_payment.destroy
      logger.info()  
      @po.update(amount_paid:@po.decrease_amount_paid(amount)  , balance:@po.cal_balance ) 
    end
    
    respond_with(@po)
  end

  private
    def set_po_payment
      @po_payment = PoPayment.find(params[:id])
    end

    def po_payment_params
      params.require(:po_payment).permit(:amount, :date, :purchase_order_id)
    end
    
    def set_po
      @po = PurchaseOrder.find(params[:purchase_order_id])
    end
    
    
   
end
